<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>HTML DOM - Paste an image from the clipboard</title>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="stylesheet" href="/css/demo.css" />
        <link rel="preconnect" href="https://fonts.gstatic.com" />
        <link
            rel="stylesheet"
            href="https://fonts.googleapis.com/css2?family=Inter&family=Source+Code+Pro&display=swap"
        />
        <style>
            .container {
                /* Center the content */
                align-items: center;
                display: flex;
                justify-content: center;

                /* Misc */
                height: 32rem;
                padding: 1rem 0;
            }
            .key {
                background-color: #f7fafc;
                border: 1px solid #cbd5e0;
                border-radius: 0.25rem;
                padding: 0.25rem;
            }
            .preview {
                align-items: center;
                border: 1px solid #cbd5e0;
                display: flex;
                justify-content: center;

                margin-top: 1rem;
                max-height: 16rem;
                max-width: 42rem;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div>
                <div><kbd class="key">Ctrl</kbd> + <kbd class="key">V</kbd> in this window.</div>
                <img class="preview" id="preview" />
            </div>
        </div>

        <script>
            document.addEventListener('DOMContentLoaded', function () {
                document.addEventListener('paste', function (evt) {
                    const clipboardItems = evt.clipboardData.items;
                    const items = [].slice.call(clipboardItems).filter(function (item) {
                        // Filter the image items only
                        return item.type.indexOf('image') !== -1;
                    });
                    if (items.length === 0) {
                        return;
                    }

                    const item = items[0];
                    const blob = item.getAsFile();

                    const imageEle = document.getElementById('preview');
                    imageEle.src = URL.createObjectURL(blob);
                });
            });
        </script>
    </body>
</html>
